import { userLogin, queryUserInfo, logout } from '@/api/user'
const user = {
  state: {
    token: '',
    name: '',
    openId: '初始openId',
    userInfo: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      wx.setStorageSync('Authorization', token);
    },
    SET_OPEN_ID: (state, openId) => {
      state.openId = openId;
      wx.setStorageSync('openId', openId);
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    }
  },

  actions: {
    // 登录
    async Login({ commit }, userInfo) {
      // 方法一 async+await  成功
      const res_data = await userLogin(userInfo)
      commit('SET_TOKEN', res_data.data.access_token)
      commit('SET_OPEN_ID', res_data.data.openId)
      wx.switchTab({
        url: '/pages/index/main'
      });
      // 方法二 new Promise 失败
      // return new Promise((resolve, reject) => {
      //   console.log('userLogin()')
      //   userLogin(userInfo).then(response => {
      //     commit('SET_TOKEN', response.data.access_token)
      //     commit('SET_OPEN_ID', response.data.openId)
      //     reject(response)
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },
    // 获取用户信息
    async GetInfo({ commit, state }) {
      const res_data = await queryUserInfo(state)
      commit('SET_USER_INFO', res_data.data.data)
    },
    // 登出
    async LogOut({ commit, state }) {
      await logout(state)
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', '')
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        console.log('FedLogOut')
        commit('SET_TOKEN', '')
        commit('SET_USER_INFO', '')
        resolve()
      })
    }
  }
}

export default user
